﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.EntityClient;
using System.Configuration;
using System.IO;

namespace GestionComercial.Model
{
    public class ManagerContext
    {
        private static Context _contexto;

        public static Context Contexto
        {
            get 
            {
                if (_contexto == null)
                {
                    _contexto = new Context();
                    CrearConnectionString();
                    
                }
                return _contexto;
            }
        }
        private static SqlConnectionStringBuilder sb { get; set; }
        public static void CrearConnectionString()
        {
            if (_contexto.Database.Connection.State == ConnectionState.Open)
                _contexto.Database.Connection.Close();
            sb = new SqlConnectionStringBuilder();

            sb.InitialCatalog = ReadAppConfig("InitialCatalog");
            sb.DataSource = ReadAppConfig("DataSource");
            sb.IntegratedSecurity = bool.Parse(ReadAppConfig("IntegratedSecurity"));
            if ((bool.Parse(ReadAppConfig("IntegratedSecurity")) == false))
            {
                sb.UserID = ReadAppConfig("usr");
                sb.Password = ReadAppConfig("pwd");
            }

            _contexto.Database.Connection.ConnectionString = sb.ConnectionString;

        }
        public static string ReadAppConfig(string _key)
        {
            string _value = "";
            _value = ConfigurationManager.AppSettings[_key];
            return _value;
        }
        public static void WriteAppConfig(string _Key, string _value)
        {
            Configuration _configuracion = ConfigurationManager.OpenExeConfiguration("GestionComercial.vshost.exe.config");
            AppSettingsSection appSettings = _configuracion.AppSettings;
            appSettings.Settings[_Key].Value = _value;
            _configuracion.Save(ConfigurationSaveMode.Modified);

        }
    }
}
